import 'dart:convert';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: buildHomePage(),
    );
  }

  Widget buildHomePage() {
    String url = window.defaultRouteName;
    // route名称
    String route = url.indexOf('?') == -1 ? url : url.substring(0, url.indexOf('?'));
    // 参数Json字符串
    String paramsJson = url.indexOf('?') == -1 ? '{}' : url.substring(url.indexOf('?') + 1);
    // 解析参数
    Map<String, dynamic> params = json.decode(paramsJson);

    if (route == null || route == "/" || route == "")
      return MyHomePage(title: params["title"] ?? "Hellow Flutter");
    return EmptyPage(data: paramsJson);
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  static const nativeChannel = const MethodChannel('com.example.flutter/native');
  static const flutterChannel = const MethodChannel('com.example.flutter/flutter');

  int _counter = 0;
  String resultMsg;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  void initState() {
    super.initState();

    Future<dynamic> handler(MethodCall call) async {
      switch (call.method) {
        case 'onActivityResult':
          setState(() {
            resultMsg = call.arguments['message'];
          });
          break;
        case 'goBack':
          // 返回上一页
          if (Navigator.canPop(context)) {
            Navigator.of(context).pop();
          } else {
            nativeChannel.invokeMethod('goBack');
          }
          break;
      }
    }

    flutterChannel.setMethodCallHandler(handler);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: WillPopScope(
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(
                resultMsg ?? 'You have pushed the button this many times:',
              ),
              Text(
                '$_counter',
                style: Theme.of(context).textTheme.display1,
              ),
              SizedBox(height: 16),
              RaisedButton(onPressed: () {
                Navigator.of(context)
                    .push(MaterialPageRoute(builder: (context) {
                  return EmptyPage();
                }));
              }, child: Text("新Flutter页")),
              RaisedButton(
                  child: Text('返回上一页'),
                  onPressed: () {
                    Map<String, dynamic> result = {'message': '我从Flutter页面回来了'};
                    nativeChannel.invokeMethod('goBackWithResult', result);
                  }),
            ],
          ),
        ),
        onWillPop: () async {
          print("返回键点击了");
          // 返回给上一页的数据
          Map<String, dynamic> result = {'message': '我从Flutter页面回来了(Backup)'};
          nativeChannel.invokeMethod('goBackWithResult', result);
          return true;
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

class EmptyPage extends StatelessWidget {
  static const nativeChannel = const MethodChannel('com.example.flutter/native');

  const EmptyPage({Key key, this.data}) : super(key: key);

  final String data;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Flutter Page"),
      ),
      body: Center(
        child: Column(
          children: <Widget>[
            Text(data ?? "无效参数"),
            SizedBox(height: 32.0),
            RaisedButton(
                child: Text('跳转Flutter页面'),
                onPressed: () {
                  Navigator.of(context)
                      .push(MaterialPageRoute(builder: (context) {
                    return EmptyPage(data: "New Flutter Page");
                  }));
                }),
            RaisedButton(
                child: Text('跳转Android原生页面'),
                onPressed: () {
                  // 跳转原生页面
                  Map<String, dynamic> result = {'name': "test"};
                  nativeChannel.invokeMethod('jumpToNative', result);
                }),
          ],
        )
      ),
    );
  }
}